package com.kaifamiao.demo.d0905;

import java.sql.*;
import java.util.Date;

public class Demo {

    public static void main(String[] args) {
        try {
            // 加载驱动类，注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/kfm";
            String user = "root";
            String password = "";
            
            // 创建数据库连接
            Connection connection = DriverManager.getConnection(url, user, password);
            // 创建 Statement 对象
            Statement statement = connection.createStatement();
            // 执行 SQL
            String sql = """
                SELECT id, username user, password pass, createDate date FROM USERS
            """;
            ResultSet resultSet = statement.executeQuery(sql);


            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount(); // 4

            // 1. getColumnLabel   getColumnName 区别
            // 2. 输出结果集
            for (int i = 1; i <= columnCount; i ++){
                String label = metaData.getColumnLabel(i);
                System.out.print(label + "\t\t");
            }
            System.out.println();
            // 解析结果集
            while(resultSet.next()) {
                int id = resultSet.getInt(1);
                String username = resultSet.getString("user");
                String pass = resultSet.getString(3);
                Date date = resultSet.getObject("date", Date.class);
                System.out.println(id + "\t\t" + username + "\t\t" + pass + "\t\t" + date);
            }

            sql = """
                    SELECT id, username user, password pass, createDate date FROM USERS
                    """;
            resultSet = statement.executeQuery(sql);
            // 解析结果集
            while(resultSet.next()) {
                int id = resultSet.getInt(1);
                String username = resultSet.getString(2);
                String pass = resultSet.getString(3);
                Date date = resultSet.getObject(4, Date.class);
                System.out.println(id + "\t\t" + username + "\t\t" + pass + "\t\t" + date);
            }
            // 释放资源
            resultSet.close();
            statement.close();
            connection.close();

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
